package com.xiongjie.v7;

import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.StampingProperties;
import com.itextpdf.signatures.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.Certificate;

public class Itext7Signaturel {

    public static String basePath="v7/src/main/resources/";

    public static void main(String[] args) throws Exception {
        sign(new FileInputStream(basePath+"hello.pdf"), new FileOutputStream(basePath+"hello_signature.pdf"),
                new FileInputStream( "/Users/admin/myKey.jks"), "123456".toCharArray());
    }

    /**
     * 在已经生成的pdf上添加电子签章，生成新的pdf并将其输出出来
     */
    public static void sign(InputStream src,OutputStream dest, InputStream p12Stream, char[] password) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(p12Stream, password);
        String alias = ks.aliases().nextElement();
        PrivateKey pk = (PrivateKey) ks.getKey(alias, password);
        Certificate[] chain = ks.getCertificateChain(alias);

        PdfReader reader = new PdfReader(src);
        StampingProperties properties = new StampingProperties();
        PdfSigner signer = new PdfSigner(reader, dest, properties);
        IExternalSignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256,  BouncyCastleProvider.PROVIDER_NAME);

        signer.signDetached(new BouncyCastleDigest(), pks, chain, null, null, null, 0, PdfSigner.CryptoStandard.CADES);
    }
}
